package com.smart.community.feign.region.fallback;

import com.smart.community.feign.region.dto.RegionHierarchyInfo;
import com.smart.community.feign.region.service.IRegionHierarchyFeign;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.openfeign.FallbackFactory;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 区域层级关系Feign降级处理工厂
 * 
 * 当区域服务不可用时，提供安全的降级处理：
 * 1. 返回安全的默认值，避免调用方异常
 * 2. 记录详细的错误日志，便于问题排查
 * 3. 确保缴费系统稳定性，避免因区域服务异常导致缴费功能完全不可用
 * 
 * @author Wu.Liang
 * @version 1.0.0
 * @since 2025-01-30
 */
@Slf4j
@Component
public class RegionHierarchyFeignFallbackFactory implements FallbackFactory<IRegionHierarchyFeign> {
    
    @Override
    public IRegionHierarchyFeign create(Throwable cause) {
        log.warn("区域服务不可用，执行降级处理: {}", cause.getMessage());
        
        return new IRegionHierarchyFeign() {
            
            @Override
            public Long getPropertyCompanyIdByHouseholdId(Long householdId) {
                log.debug("服务降级：getPropertyCompanyIdByHouseholdId方法，房户ID: {}", householdId);
                return null; // ✅ 返回null，表示无法获取物业公司ID
            }
            
            @Override
            public RegionHierarchyInfo getRegionHierarchyByHouseholdId(Long householdId) {
                log.debug("服务降级：getRegionHierarchyByHouseholdId方法，房户ID: {}", householdId);
                // ✅ 返回空对象，避免NullPointerException
                RegionHierarchyInfo info = new RegionHierarchyInfo();
                info.setHouseholdId(householdId); // 至少保留传入的房户ID
                return info;
            }
            
            @Override
            public Map<Long, Long> getPropertyCompanyIdsByHouseholdIds(List<Long> householdIds) {
                log.debug("服务降级：getPropertyCompanyIdsByHouseholdIds方法，房户ID列表: {}", householdIds);
                return new HashMap<>(); // ✅ 返回空Map，表示批量查询失败
            }
            
            @Override
            public Long getCommunityIdByHouseholdId(Long householdId) {
                log.debug("服务降级：getCommunityIdByHouseholdId方法，房户ID: {}", householdId);
                return null; // ✅ 返回null，表示无法获取社区ID
            }
            
            @Override
            public Map<Long, Long> getCommunityIdsByHouseholdIds(List<Long> householdIds) {
                log.debug("服务降级：getCommunityIdsByHouseholdIds方法，房户ID列表: {}", householdIds);
                return new HashMap<>(); // ✅ 返回空Map，表示批量查询失败
            }
        };
    }
}
